package com.dshore.messagecenter.controller.system;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.entity.ContentType;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.baidu.aip.ocr.AipOcr;
import com.dshore.messagecenter.controller.basedata.BaseController;
import com.dshore.messagecenter.model.ExcelUp;
import com.dshore.messagecenter.model.MongoUser;
import com.dshore.messagecenter.model.system.User;
import com.dshore.messagecenter.service.basedata.LoginService;
import com.dshore.messagecenter.util.OssClienUtils;
import com.dshore.messagecenter.util.ShiroUtils;
import com.dshore.messagecenter.util.UUIDUtil;

@Controller
@RequestMapping("/index")
public class SysChangeStyleController extends BaseController{
	// 设置APPID/AK/SK
	public static final String APP_ID = "15588409";    //你的 App ID
	public static final String API_KEY = "obOZYORkeHjZqfwV6VUKj8it";   //你的 Api Key
	public static final String SECRET_KEY = "vg74dAOROiGGhsmS3yXcQ6ousvRxbs2Q";//你的Secret
	
	public static final String APP_ID1="15598247";
	public static final String API_KEY1 = "NKIGyshoj7QWzr63x80rdnPc"; 
	public static final String SECRET_KEY1 = "Io6jkapngBMUMUB7GbgzvbRjPlT6TNFq";
	
	private static final String SUFFIX_2003 = ".xls";
    private static final String SUFFIX_2007 = ".xlsx";
	
	@Autowired
	private LoginService loginService;
	
	//修改页面风格
	@RequestMapping("/toChangeStyle")
	public ModelAndView IntoChangeStyle() {
		ModelAndView mv=new ModelAndView("system/changeStyle");
		//mv.setViewName("changeStyle");
		return mv;
	}	
	
	//验证redis
	@RequestMapping(value="/addredis",method=RequestMethod.POST)
	@ResponseBody
	public int addredis(@RequestParam("username")String username,@RequestParam("password")String password,@RequestParam("tel")String tel) {
		int result=loginService.addredis(username,password,tel);
		return result;
	}	
	
	//验证addmongoDB
	@RequestMapping(value="/addmongoDB",method=RequestMethod.POST)
	@ResponseBody
	public int addmongoDB(@RequestParam("username")String username,@RequestParam("password")String password,@RequestParam("tel")String tel) {
		int result=loginService.addmongoDB(username,password,tel);
		return result;
	}	
	
	//查找redis
	@RequestMapping(value="/lookredis",method=RequestMethod.POST)
	@ResponseBody
	public List<User> lookredis(@RequestParam("id")String id){
		List<User> result=loginService.lookredis(id);
		return result;
	}
	
	//查找mongoDB
	@RequestMapping(value="/lookmongoDB",method=RequestMethod.POST)
	@ResponseBody
	public MongoUser lookmongoDB(@RequestParam("name")String name){
		System.out.println("name----------:"+name);
		MongoUser result=loginService.lookmongoDB(name);
		System.out.println("result--------------:"+result);
		return result;
	}	
	
	//身份证正面识别
	@RequestMapping(value="/sfz",method=RequestMethod.POST)
	@ResponseBody
	public String sfz(@RequestParam("name")String name) throws JSONException{
		// 初始化一个AipOcr
		AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
	    HashMap<String, String> options = new HashMap<String, String>();
	    options.put("detect_direction", "true");
	    options.put("detect_risk", "false");
		String idCardSide = "front"; 
	    // 参数为本地图片路径
		String image = "E:/一些照片/证件照/aaa.png";
		JSONObject res = client.idcard(image,idCardSide, options);
		return res.toString(2);
	}
	
	//身份证反面识别
	@RequestMapping(value="/sfzf",method=RequestMethod.POST)
	@ResponseBody
	public String sfzf(@RequestParam("name")String name) throws JSONException{
		// 初始化一个AipOcr
		AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
	    HashMap<String, String> options = new HashMap<String, String>();
	    options.put("detect_direction", "true");
	    options.put("detect_risk", "false");
		String idCardSide = "back"; 
	    // 参数为本地图片路径
		String image = "E:/一些照片/证件照/bbb.png";
		JSONObject res = client.idcard(image,idCardSide, options);
		return res.toString(2);
	}
	
	//单向散列函数SHA2
	@RequestMapping(value="/sha",method=RequestMethod.POST)
	@ResponseBody
	public String[] sha(@RequestParam("name")String name) {
		String password=name;
		String salt="吃了么";
		System.out.println("name:"+password);
		String md5=DigestUtils.md5Hex(password+salt);
		System.out.println("md5加密后:"+md5);
		String re=ShiroUtils.sha256(password,salt);
		System.out.println("sha256加密:"+re);
		String[] result=new String[] {md5,re};
		return result;
	}
	
	//营业执照识别
	@RequestMapping(value="/xydm",method=RequestMethod.POST)
	@ResponseBody
	public String xydm(@RequestParam("name")String name) throws JSONException{
		// 初始化一个AipOcr
		AipOcr client = new AipOcr(APP_ID1, API_KEY1, SECRET_KEY1);
		HashMap<String, String> options = new HashMap<String, String>();
		// 参数为本地图片路径
		String image = "E:/一些照片/证件照/ccc.png";
		//String image = "https://kk-oss.oss-cn-shanghai.aliyuncs.com/iAOtjuiFJoBUBEez7koRwDVJGDYsEEkM.png";
		JSONObject res = client.businessLicense(image, options);
		return res.toString(2);
	}	
	
	//2数据库保存excel
	@RequestMapping(value="/upexcel",method=RequestMethod.POST)
	@ResponseBody
	public Integer upexcel(@RequestParam MultipartFile file) throws IOException {
		String originalFilename = file.getOriginalFilename();
		System.out.println("suffix:"+originalFilename);
		List<ExcelUp> list = new ArrayList<ExcelUp>();
		Integer r=0;
		
		//创建excel 
		Workbook workbook=null;
		
		if (originalFilename.endsWith(SUFFIX_2003)) {
            workbook = new HSSFWorkbook(file.getInputStream());
        } else if (originalFilename.endsWith(SUFFIX_2007)) {
            workbook = new XSSFWorkbook(file.getInputStream());
        }
		
		if (workbook == null) {
		    //格式错误
		}else {
			//获取所有的工作表的的数量
            int numOfSheet = workbook.getNumberOfSheets();
            //遍历这个这些表
            for (int i = 0; i < numOfSheet; i++) {
            	//获取第一个sheet也就是一个工作簿
                Sheet sheet = workbook.getSheetAt(0);
                //获取sheet中第一行行号
        		int firstRowNum = sheet.getFirstRowNum();
        		//获取sheet中最后一行行号
        		int lastRowNum = sheet.getLastRowNum();
        		
        		try {
        			//循环插入数据
        			for(int j=firstRowNum+1;j<=lastRowNum;j++){
        				Row row = sheet.getRow(j);
        				ExcelUp eu = new ExcelUp();
        				
        				Cell username = row.getCell(0);//第一列
        				if(username!=null ||username==null){
        					username.setCellType(Cell.CELL_TYPE_STRING);
        					System.out.println(username.getStringCellValue());
        					eu.setName1((username.getStringCellValue()));
        				}
        				
        				Cell phone = row.getCell(1);//第二列
        				if(phone!=null || phone==null){
        					phone.setCellType(Cell.CELL_TYPE_STRING);
        					eu.setName2((phone.getStringCellValue()));
        				}
        				eu.setId(UUIDUtil.getUUId());
        				list.add(eu);
        			}
        			//usersMapper.insert(list);//往数据库插入数据
        			r=loginService.insertExcel(list);
        			System.out.println("r:"+r);
        		} catch (Exception e) {
        			e.printStackTrace();
        		} 
            }
		}
		return r;
	}
	
	//下载excel
	@RequestMapping(value="/xzexcel",method=RequestMethod.POST)
	@ResponseBody
	public String xzexcel(@RequestParam("name")String name) throws FileNotFoundException, IOException {
		HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("信息表");
        List<ExcelUp> classmateList = loginService.xzexcel();
        String fileName = "userinf"  + ".xls";//设置要导出的文件的名字
        //新增数据行，并且设置单元格数据
        int rowNum = 1;
        //headers表示excel表中第一行的表头
        String[] headers = { "id", "name1", "name2"};
        //在excel表中添加表头
        HSSFRow row = sheet.createRow(0);
        for(int i=0;i<headers.length;i++){
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }
        
        //在表中存放查询到的数据放入对应的列
        for (ExcelUp eu : classmateList) {
            HSSFRow row1 = sheet.createRow(rowNum);
            row1.createCell(0).setCellValue(eu.getId());
            row1.createCell(1).setCellValue(eu.getName1());
            row1.createCell(2).setCellValue(eu.getName2());
            rowNum++;
        }
        workbook.write(new FileOutputStream("E:"+fileName));
        String a="1";
		return a;
	}
	
	//上传图片
	@RequestMapping(value="/upload1",method=RequestMethod.POST)
	@ResponseBody
	public String upload1(@RequestParam("name")String name) throws Exception {
		File f = new File("C:/Users/panyi-com/Desktop/abc.png");
		FileInputStream fileInputStream = new FileInputStream(f);
		MultipartFile file = new MockMultipartFile(f.getName(), f.getName(),
							ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
		
		//上传的文件名 + 后缀    如  asd.png
		String  nameHz= file.getOriginalFilename();
		System.out.println("nameHz:"+nameHz);
		String type = "";
        if(nameHz.contains(".png") || nameHz.contains(".jpg")){
            type="/img";
        }
        if(nameHz.contains(".mp4") || nameHz.contains(".ogv")){
            type="/video";
        }else {
            type="/file";
        }
        OssClienUtils ossClient = new OssClienUtils();
        String keyName = ossClient.uploadImg2Oss(file,type);
        String imgUrl = ossClient.getImgUrl(keyName);
        System.out.println("imgUrl--------"+imgUrl);
        
        
		return "ok";
	}
	
	
}
